'use client';
import { useRouter } from 'next/navigation';
import { useEffect, useState, useRef, use } from 'react';
import { useSession } from 'next-auth/react';
import { Spinner } from '@/components/ui/Spinner';
import Image from 'next/image';
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Check, Copy, Send, Settings2, Eraser, HelpCircle } from "lucide-react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import ChatTest from '@/components/chat/ChatTest';
import { useLanguage } from '@/contexts/LanguageContext';
import { useToast } from "@/hooks/use-toast"
import dynamic from 'next/dynamic';
import { Loader2, Wand2 } from "lucide-react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalTitle,
} from "@/components/ui/modal"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

const STORAGE_KEY = 'chat_settings';

// SSR安全的可搜索下拉组件
const TemplateSelect = dynamic(() => import('react-select'), { ssr: false });

// 变量替换弹窗组件
const VariableReplacementModal = ({ isOpen, onClose, variables, onConfirm, promptContent }) => {
  const [variableValues, setVariableValues] = useState({});
  const { t } = useLanguage();

  useEffect(() => {
    if (isOpen && variables.length > 0) {
      const initialValues = {};
      variables.forEach(variable => {
        initialValues[variable] = '';
      });
      setVariableValues(initialValues);
    }
  }, [isOpen, variables]);

  const handleConfirm = () => {
    // 检查是否所有变量都已填写
    const allFilled = variables.every(variable => variableValues[variable]?.trim());
    if (!allFilled) {
      return;
    }
    
    // 替换提示词中的变量
    let replacedContent = promptContent;
    variables.forEach(variable => {
      const regex = new RegExp(`\\{\\{${variable}\\}\\}`, 'g');
      replacedContent = replacedContent.replace(regex, variableValues[variable]);
    });
    
    onConfirm(replacedContent);
    onClose();
  };

  const handleCancel = () => {
    onClose();
  };

  if (!isOpen) return null;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>变量替换</DialogTitle>
          <DialogDescription>
            请为以下变量输入替换内容：
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4 py-4">
          {variables.map((variable) => (
            <div key={variable} className="space-y-2">
              <Label htmlFor={variable} className="text-sm font-medium">
                {variable}
              </Label>
              <Input
                id={variable}
                value={variableValues[variable] || ''}
                onChange={(e) => setVariableValues(prev => ({
                  ...prev,
                  [variable]: e.target.value
                }))}
                placeholder={`请输入 ${variable} 的值`}
                className="w-full"
              />
            </div>
          ))}
        </div>
        
        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            取消
          </Button>
          <Button 
            onClick={handleConfirm}
            disabled={!variables.every(variable => variableValues[variable]?.trim())}
          >
            确定
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

const TypewriterText = ({ text }) => {
  return (
    <span className="typing-effect">
      {text}
    </span>
  );
};

const PromptSkeleton = () => {
  const { t } = useLanguage();
  if (!t) return null;
  const tp = t.promptDetailPage;
  return (
    <div className="container mx-auto p-4 sm:p-6 max-w-7xl">
      <div className="flex items-center space-x-2 mb-4">
        <Button
          variant="ghost"
          className="text-muted-foreground hover:bg-secondary"
          disabled
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          {tp?.backToList || 'Back to Prompt List'}
        </Button>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
        <div className="h-full flex flex-col">
          <Card className="border-none shadow-lg bg-gradient-to-br from-background to-secondary/10 flex-1">
            <CardContent className="p-4 sm:p-6">
              <div className="space-y-4">
                <Skeleton className="h-8 w-2/3" />
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-4/5" />
                <div className="flex gap-2">
                  <Skeleton className="h-6 w-20" />
                  <Skeleton className="h-6 w-20" />
                </div>
              </div>
              <div className="mt-6">
                <Skeleton className="h-[300px] w-full" />
              </div>
            </CardContent>
          </Card>
        </div>

        <div className="h-full">
          <Card className="h-full">
            <CardHeader>
              <div className="flex justify-between items-center">
                <Skeleton className="h-8 w-32" />
                <Skeleton className="h-8 w-8" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <Skeleton className="h-[400px] w-full" />
                <div className="flex gap-2">
                  <Skeleton className="h-[50px] flex-1" />
                  <Skeleton className="h-[50px] w-[50px]" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default function PromptDetail({ params }) {
  const { id } = use(params);
  const router = useRouter();
  const { t } = useLanguage();
  const { toast } = useToast();
  const { data: session } = useSession();
  const [prompt, setPrompt] = useState(null);
  const [copySuccess, setCopySuccess] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [shareSuccess, setShareSuccess] = useState(false);
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isSending, setIsSending] = useState(false);
  // 移除未使用的 showSettings，避免与聊天设置混淆
  const [apiKey, setApiKey] = useState(() => {
    if (typeof window !== 'undefined') {
      const savedSettings = localStorage.getItem(STORAGE_KEY);
      return savedSettings ? JSON.parse(savedSettings).apiKey : '';
    }
    return '';
  });
  const [selectedModel, setSelectedModel] = useState('glm-4-flash');
  const [isLoading, setIsLoading] = useState(false);
  const [useCustomKey, setUseCustomKey] = useState(false);
  const [temperature, setTemperature] = useState(0.5);
  const [isEditing, setIsEditing] = useState(false);
  const [editedContent, setEditedContent] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const messagesEndRef = useRef(null);
  const editorRef = useRef(null);
  const chatTestRef = useRef(null);
  const [copiedMessageId, setCopiedMessageId] = useState(null);
  const [customModel, setCustomModel] = useState(() => {
    if (typeof window !== 'undefined') {
      const savedSettings = localStorage.getItem(STORAGE_KEY);
      return savedSettings ? JSON.parse(savedSettings).model : 'glm-4-flash';
    }
    return 'glm-4-flash';
  });
  const [baseUrl, setBaseUrl] = useState(() => {
    if (typeof window !== 'undefined') {
      const savedSettings = localStorage.getItem(STORAGE_KEY);
      return savedSettings ? JSON.parse(savedSettings).baseUrl : 'https://open.bigmodel.cn/api/paas/v4';
    }
    return 'https://open.bigmodel.cn/api/paas/v4';
  });
  const [versions, setVersions] = useState([]);
  const [selectedVersion, setSelectedVersion] = useState(null);
  const [templates, setTemplates] = useState([]);
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);
  const menuPortalTarget = typeof window !== 'undefined' ? document.body : undefined;
  const [showVariableModal, setShowVariableModal] = useState(false);
  const [detectedVariables, setDetectedVariables] = useState([]);
  const [pendingMessage, setPendingMessage] = useState(null);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [showOptimizeModal, setShowOptimizeModal] = useState(false);
  const [showModelSettings, setShowModelSettings] = useState(false);
  const [modelConfig, setModelConfig] = useState({
    id: null,
    channel: '',
    channel_id: null,
    model: '',
    temperature: 1.0,
    max_tokens: 2048,
    top_p: 1.0,
    presence_penalty: 0.0,
    frequency_penalty: 0.0,
    n: 1,
    stop: '',
    logit_bias: '',
    stream: true,
    api_key: ''
  });

  const [channels, setChannels] = useState([]);
  const [models, setModels] = useState([]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  // 检测提示词中的变量
  const detectVariables = (content) => {
    const variableRegex = /\{\{([^}]+)\}\}/g;
    const variables = [];
    let match;
    
    while ((match = variableRegex.exec(content)) !== null) {
      const variableName = match[1].trim();
      if (!variables.includes(variableName)) {
        variables.push(variableName);
      }
    }
    
    return variables;
  };

  // 处理变量替换
  const handleVariableReplacement = (replacedContent) => {
    // 更新编辑内容（如果正在编辑）或提示词内容
    if (isEditing) {
      setEditedContent(replacedContent);
    } else {
      // 如果不在编辑状态，更新提示词内容
      setPrompt(prev => ({ ...prev, content: replacedContent }));
    }
    setShowVariableModal(false);
    
    // 如果有待发送的消息，延迟一点时间确保状态更新完成后再发送
    if (pendingMessage) {
      setTimeout(() => {
        // 通知 ChatTest 组件继续发送消息
        if (chatTestRef.current && chatTestRef.current.retrySendMessage) {
          chatTestRef.current.retrySendMessage();
        }
        setPendingMessage(null);
      }, 100); // 延迟100ms确保状态更新完成
    }
  };

  // 获取当前提示词内容（优先使用编辑中的内容）
  const getCurrentPromptContent = () => {
    return isEditing ? editedContent : (prompt?.content || '');
  };

  // 检查是否需要变量替换
  const checkAndHandleVariables = (content) => {
    // 使用当前显示在输入框中的内容来检测变量
    const currentContent = getCurrentPromptContent();
    const variables = detectVariables(currentContent);
    if (variables.length > 0) {
      setDetectedVariables(variables);
      setShowVariableModal(true);
      setPendingMessage(true); // 标记有待发送的消息
      return true; // 需要变量替换
    }
    return false; // 不需要变量替换
  };

  // 提示词优化功能
  const handleOptimize = async () => {
    const currentContent = getCurrentPromptContent();
    if (!currentContent.trim()) return;
    
    setIsOptimizing(true);
    setOptimizedContent('');
    setShowOptimizeModal(true);
    
    try {
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: currentContent }),
      });
      
      if (!response.ok) throw new Error('优化失败');
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let tempContent = '';
      let isStreamComplete = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          isStreamComplete = true;
          break;
        }
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());
        
        for (const line of lines) {
          try {
            const jsonStr = line.replace(/^data: /, '').trim();
            if (!jsonStr || jsonStr === '[DONE]') {
              isStreamComplete = true;
              continue;
            }
            
            const data = JSON.parse(jsonStr);
            if (data.choices?.[0]?.delta?.content) {
              tempContent += data.choices[0].delta.content;
              setOptimizedContent(tempContent);
            }
          } catch (e) {
            console.error('解析优化结果失败', e);
          }
        }
      }

      // 确保流式输出完成
      if (isStreamComplete) {
        setIsOptimizing(false);
      }

    } catch (error) {
      console.error('优化错误', error);
      toast({
        variant: "destructive",
        description: '优化失败',
        duration: 3000,
      });
      setIsOptimizing(false);
    }
  };

  const handleApplyOptimized = () => {
    if (isEditing) {
      setEditedContent(optimizedContent);
    } else {
      setPrompt(prev => ({ ...prev, content: optimizedContent }));
    }
    setShowOptimizeModal(false);
  };

  const validateModelConfig = () => {
    // 渠道名称必填
    if (!modelConfig.channel || modelConfig.channel.trim() === '') {
      toast({ variant: 'destructive', description: '渠道名称不能为空' });
      return false;
    }
    // 模型名称必填
    if (!modelConfig.model || modelConfig.model.trim() === '') {
      toast({ variant: 'destructive', description: '模型名称不能为空' });
      return false;
    }
    // temperature [0,2]
    const temperature = Number(modelConfig.temperature);
    if (Number.isNaN(temperature) || temperature < 0 || temperature > 2) {
      toast({ variant: 'destructive', description: 'temperature 取值范围应在 [0, 2]' });
      return false;
    }
    // top_p [0,2]
    const top_p = Number(modelConfig.top_p);
    if (Number.isNaN(top_p) || top_p < 0 || top_p > 2) {
      toast({ variant: 'destructive', description: 'top_p 取值范围应在 [0, 2]' });
      return false;
    }
    // max_tokens [10,30000]
    const max_tokens = Number(modelConfig.max_tokens);
    if (Number.isNaN(max_tokens) || max_tokens < 10 || max_tokens > 30000) {
      toast({ variant: 'destructive', description: 'max_tokens 取值范围应在 [10, 30000]' });
      return false;
    }
    // presence_penalty [-2,2]
    const presence_penalty = Number(modelConfig.presence_penalty);
    if (Number.isNaN(presence_penalty) || presence_penalty < -2 || presence_penalty > 2) {
      toast({ variant: 'destructive', description: 'presence_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    // frequency_penalty [-2,2]
    const frequency_penalty = Number(modelConfig.frequency_penalty);
    if (Number.isNaN(frequency_penalty) || frequency_penalty < -2 || frequency_penalty > 2) {
      toast({ variant: 'destructive', description: 'frequency_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    return true;
  };

  const handleSaveModelConfig = async () => {
    try {
      // 校验模型配置（必填项及范围）
      if (!validateModelConfig()) {
        return;
      }

      // 准备模型数据
      const modelData = {
        id: modelConfig.id, // 保留模型ID，用于更新现有模型
        channel_id: modelConfig.channel_id,
        channel: modelConfig.channel,
        model: modelConfig.model,
        temperature: Number(modelConfig.temperature),
        max_tokens: Number(modelConfig.max_tokens),
        top_p: Number(modelConfig.top_p),
        presence_penalty: Number(modelConfig.presence_penalty),
        frequency_penalty: Number(modelConfig.frequency_penalty),
        n: Number(modelConfig.n),
        stop: modelConfig.stop ? modelConfig.stop.split(',').map(s => s.trim()).filter(Boolean) : null,
        logit_bias: modelConfig.logit_bias ? JSON.parse(modelConfig.logit_bias) : null,
        stream: Boolean(modelConfig.stream),
        api_key: modelConfig.api_key
      };

      // 调用API保存模型配置
      const response = await fetch(`/api/prompts/updatePromptsById`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          prompt: {
            id: id,  // 将id放入prompt对象中
            title: prompt.title,
            content: prompt.content,
            description: prompt.description,
            tags: Array.isArray(prompt.tags) ? prompt.tags.join(',') : (prompt.tags || ''),
            version: prompt.version
          },
          model: modelData
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || errorData.error || '保存失败');
      }

      toast({
        title: "成功",
        description: "模型配置已保存",
      });
      setShowModelSettings(false);
    } catch (error) {
      console.error('Error saving model config:', error);
      const errorMessage = error.message || '保存失败，请重试';
      toast({
        title: "错误",
        description: errorMessage,
        variant: "destructive",
      });
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    if (id) {
      // 获取提示词信息
      fetch(`/api/prompts/${id}`)
        .then((response) => response.json())
        .then((data) => {
          setPrompt({...data, tags: data.tags ? data.tags.split(',') : []});
          setSelectedVersion(data.version);
          // 如果有模型ID，获取模型信息
          if (data.model_id) {
            fetch(`/api/models/${data.model_id}`)
              .then(res => res.json())
              .then(m => {
                setModelConfig({
                  id: m.id,
                  channel: m.channel || '',
                  channel_id: m.channel_id || null,
                  model: m.model || '',
                  temperature: m.temperature ?? 1.0,
                  max_tokens: m.max_tokens ?? 2048,
                  top_p: m.top_p ?? 1.0,
                  presence_penalty: m.presence_penalty ?? 0.0,
                  frequency_penalty: m.frequency_penalty ?? 0.0,
                  n: m.n ?? 1,
                  stop: (m.stop && Array.isArray(m.stop)) ? m.stop.join(',') : '',
                  logit_bias: m.logit_bias ? JSON.stringify(m.logit_bias) : '',
                  stream: !!m.stream,
                  response_format: m.response_format || '',
                  endpoint_url: m.endpoint_url || '',
                  file_path: m.file_path || '',
                  api_key: m.api_key || ''
                })
              })
              .catch(() => {})
          }
          // 获取版本信息（需在此作用域使用 data.title）
          fetch(`/api/prompts?title=${encodeURIComponent(data.title)}`)
            .then((response) => response.json())
            .then((versionsData) => {
              const sameTitle = versionsData.filter(v => v.title === data.title);
              setVersions(sameTitle.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)));
            })
            .catch((error) => console.error('Error fetching versions:', error));
        })
        .catch((error) => console.error('Error fetching prompt:', error));
    }
  }, [id]);

  // 加载模板列表
  useEffect(() => {
    const loadTemplates = async () => {
      try {
        setIsLoadingTemplates(true);
        const res = await fetch('/api/templates');
        if (!res.ok) throw new Error('加载模板失败');
        const data = await res.json();
        setTemplates(Array.isArray(data) ? data : []);
      } catch (e) {
        console.error('加载模板失败:', e);
        toast({ title: '错误', description: '加载模板失败', variant: 'destructive' });
      } finally {
        setIsLoadingTemplates(false);
      }
    };
    loadTemplates();
  }, [toast]);

  // 获取渠道信息
  useEffect(() => {
    const fetchChannels = async () => {
      if (!session?.user?.accessToken) return;
      
      try {
        const response = await fetch(`/api/models/channels`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setChannels(data.data);
        }
      } catch (error) {
        console.error('Error fetching channels:', error);
      }
    };

    fetchChannels();
  }, [session?.user?.accessToken]);

  // 当渠道改变时，获取对应的模型列表
  useEffect(() => {
    const fetchModels = async () => {
      if (!modelConfig.channel_id || !session?.user?.accessToken) {
        setModels([]);
        return;
      }

      try {
        const response = await fetch(`/api/models/models/${modelConfig.channel_id}`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setModels(data.data);
        }
      } catch (error) {
        console.error('Error fetching models:', error);
      }
    };

    fetchModels();
  }, [modelConfig.channel_id, session?.user?.accessToken]);

  const handleApplyTemplate = (option) => {
    const tpl = templates.find(t => t.id === option?.value);
    if (!tpl) return;
    setIsEditing(true);
    setEditedContent(tpl.content || '');
    toast({ title: '已应用模板', description: tpl.name });
  };

  if (!t) return <PromptSkeleton />;
  const tp = t.promptDetailPage;

  const handleCopy = async () => {
    try {
      // 复制当前输入框中的内容，而不是数据库中的内容
      const contentToCopy = getCurrentPromptContent();
      await navigator.clipboard.writeText(contentToCopy);
      setCopySuccess(true);
      toast({
        title: tp.copySuccessTitle,
        description: tp.copySuccessDescription,
      });
      setTimeout(() => setCopySuccess(false), 2000);
    } catch (err) {
      console.error('Failed to copy text:', err);
      toast({
        title: tp.copyErrorTitle,
        description: tp.copyErrorDescription,
        variant: "destructive",
      });
    }
  };

  const handleDelete = async () => {
    try {
      const response = await fetch(`/api/prompts/${id}`, {
        method: 'DELETE',
      });
      
      if (response.ok) {
        router.push('/prompts');
      } else {
        throw new Error(tp.deleteError);
      }
    } catch (error) {
      console.error('Error deleting prompt:', error);
      toast({ 
        title: "Error",
        description: tp.deleteError,
        variant: "destructive",
      });
    }
  };

  const handleShare = async () => {
    try {
      const response = await fetch(`/api/prompts/share/${id}`, {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('Share failed');
      }

      const shareUrl = `${window.location.origin}/share/${id}`;
      await navigator.clipboard.writeText(shareUrl);
      setShareSuccess(true);
      toast({
        title: tp.shareSuccessTitle,
        description: tp.shareSuccessDescription,
      });
      setTimeout(() => setShareSuccess(false), 2000);
    } catch (err) {
      console.error('Failed to share prompt:', err);
      toast({
        title: tp.shareErrorTitle,
        description: tp.shareErrorDescription,
        variant: "destructive",
      });
    }
  };

  const handleSaveContent = async () => {
    // 校验：提示词内容不能为空
    if (!editedContent || editedContent.trim() === '') {
      toast({ title: '错误', description: '提示词内容不能为空', variant: 'destructive' });
      return;
    }
    setIsSaving(true);
    const previousContent = prompt.content;
    setPrompt(prev => ({...prev, content: editedContent}));
    setIsEditing(false);

    try {
      const response = await fetch(`/api/prompts/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          title: prompt.title,
          content: editedContent,
          description: prompt.description || '',
          tags: Array.isArray(prompt.tags) ? prompt.tags.join(',') : (prompt.tags || ''), // 修复：数组转字符串
          version: prompt.version || '1.0'
        })
      });

      if (!response.ok) {
        throw new Error(tp.saveError);
      }
      toast({
        title: "Success",
        description: "Content saved successfully.",
      });
      router.push(`/prompts/${id}`);
    } catch (error) {
      console.error('Error saving content:', error);
      setPrompt(prev => ({...prev, content: previousContent}));
      setIsEditing(true);
      toast({ 
        title: "Error",
        description: tp.saveError,
        variant: "destructive",
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleClearEdited = () => {
    setEditedContent('');
    setIsEditing(true);
    // 聚焦到文本域
    if (editorRef.current) {
      editorRef.current.focus();
    }
  };

  const handleCopyMessage = async (content, index) => {
    try {
      await navigator.clipboard.writeText(content);
      setCopiedMessageId(index);
    } catch (err) {
      console.error('Failed to copy text:', err);
    }
  };

  const saveSettings = (settings) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  };

  const handleApiKeyChange = (e) => {
    const newApiKey = e.target.value;
    setApiKey(newApiKey);
    saveSettings({
      apiKey: newApiKey,
      model: customModel,
      baseUrl: baseUrl
    });
  };

  const handleModelChange = (e) => {
    const newModel = e.target.value;
    setCustomModel(newModel);
    saveSettings({
      apiKey: apiKey,
      model: newModel,
      baseUrl: baseUrl
    });
  };

  const handleBaseUrlChange = (e) => {
    const newBaseUrl = e.target.value;
    setBaseUrl(newBaseUrl);
    saveSettings({
      apiKey: apiKey,
      model: customModel,
      baseUrl: newBaseUrl
    });
  };

  const handleVersionChange = (version) => {
    const selectedPrompt = versions.find(v => v.version === version);
    if (selectedPrompt) {
      router.push(`/prompts/${selectedPrompt.id}`);
    }
  };

  if (!prompt) {
    return <PromptSkeleton />;
  }

  return (
    <div className="container mx-auto p-4 sm:p-6 max-w-7xl">
      <div className="flex items-center space-x-2 mb-6">
        <Button
          variant="ghost"
          className="text-muted-foreground hover:bg-secondary"
          onClick={() => router.push('/prompts')}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          {tp.backToList}
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="h-[calc(100vh-12rem)] flex flex-col">
          <Card className="border-none shadow-lg bg-gradient-to-br from-background to-secondary/10 flex-1 overflow-hidden flex flex-col">
            <CardContent className="p-6 sm:p-8 flex flex-col h-full">
              <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-6 mb-8">
                <div className="space-y-4">
                  <h1 className="text-3xl sm:text-4xl font-bold">
                    {prompt.title}
                  </h1>
                  <p className="text-sm text-muted-foreground leading-relaxed">
                    {prompt.description}
                  </p>
                  <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <div className="flex items-center gap-1">
                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                        {new Date(prompt.created_at).toLocaleDateString()}
                      </div>
                      <span>•</span>
                      <div className="flex items-center gap-1">
                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                        </svg>
                        <span> version </span>
                        {versions.length > 1 ? (
                          <Select
                            value={selectedVersion}
                            onValueChange={handleVersionChange}
                          >
                            <SelectTrigger className="h-5 text-xs border-none bg-transparent hover:bg-secondary/50 transition-colors">
                              <SelectValue placeholder={tp.selectVersionPlaceholder}>
                                v{selectedVersion}
                              </SelectValue>
                            </SelectTrigger>
                            <SelectContent>
                              {versions.map((version) => (
                                <SelectItem 
                                  key={version.id} 
                                  value={version.version}
                                  className="text-xs"
                                >
                                  v{version.version} ({new Date(version.created_at).toLocaleDateString()})
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        ) : (
                          <span>v{prompt.version}</span>
                        )}
                      </div>
                    </div>
                    {prompt.tags?.length > 0 && prompt.tags.map((tag) => (
                      <Badge 
                        key={tag} 
                        variant="secondary"
                        className="bg-primary/5 hover:bg-primary/10 transition-colors duration-200"
                      >
                        {tag}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div className="flex gap-3">
                  <Button
                    onClick={handleShare}
                    variant={shareSuccess ? "success" : "secondary"}
                    className="relative overflow-hidden group w-10 h-10 p-0"
                    title={tp.shareTooltip}
                  >
                    <svg className={`w-4 h-4 transition-transform duration-300 ${shareSuccess ? "rotate-0" : "rotate-0"}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                    </svg>
                  </Button>

                  <Button
                    onClick={() => {
                      router.push(`/prompts/${id}/edit`, {
                        state: {
                          prompt: {
                            ...prompt,
                            tags: prompt.tags.join(',')
                          }
                        }
                      });
                    }}
                    variant="default"
                    className="relative overflow-hidden group w-10 h-10 p-0"
                    title={tp.editTooltip}
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                  </Button>

                  <Button
                    onClick={() => setShowDeleteConfirm(true)}
                    variant="destructive"
                    className="relative overflow-hidden group w-10 h-10 p-0"
                    title={tp.deleteTooltip}
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </Button>
                </div>
              </div>

              <Card className="flex-1 border border-primary/10 bg-secondary/5 backdrop-blur-sm overflow-hidden flex flex-col">
                <CardHeader className="flex flex-row items-center justify-between shrink-0">
                  <CardTitle className="text-xl font-semibold flex items-center">
                    <span className="bg-primary/10 p-2 rounded-lg mr-3">
                      <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                    </span>
                    {tp.contentCardTitle}
                  </CardTitle>
                  <div className="flex gap-2">
                    {isEditing && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={handleClearEdited}
                        className="transition-all duration-200"
                        title="清空输入"
                      >
                        <Eraser className="w-4 h-4" />
                      </Button>
                    )}
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleCopy}
                      className="transition-all duration-200"
                    >
                      {copySuccess ? (
                        <Check className="w-4 h-4 text-green-500" />
                      ) : (
                        <Copy className="w-4 h-4" />
                      )}
                    </Button>
                    {isEditing ? (
                      <>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setIsEditing(false);
                            setEditedContent(prompt.content);
                          }}
                          disabled={isSaving}
                        >
                          {tp.cancel}
                        </Button>
                        <Button
                          variant="default"
                          size="sm"
                          onClick={handleSaveContent}
                          disabled={isSaving || !editedContent || editedContent.trim() === ''}
                        >
                          {isSaving ? (
                            <span className="flex items-center gap-1">
                              <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                              </svg>
                              {tp.saving}
                            </span>
                          ) : tp.save}
                        </Button>
                      </>
                    ) : (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => {
                          setIsEditing(true);
                          setEditedContent(prompt.content);
                        }}
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                        </svg>
                      </Button>
                    )}
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleOptimize}
                      disabled={isOptimizing || !getCurrentPromptContent().trim()}
                      className="transition-all duration-200"
                      title="优化提示词"
                    >
                      {isOptimizing ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Wand2 className="w-4 h-4" />
                      )}
                    </Button>
                  </div>
                </CardHeader>
                <CardContent className="flex-1 p-0 overflow-hidden">
                  <ScrollArea className="h-full w-full">
                    <div className="rounded-lg bg-secondary/30 p-4 min-h-full">
                      {isEditing ? (
                        <div className="min-h-[500px]">
                          <Textarea
                            ref={editorRef}
                            value={editedContent}
                            onChange={(e) => setEditedContent(e.target.value)}
                            className="w-full h-full min-h-[500px] text-base leading-relaxed whitespace-pre-wrap text-primary"
                            placeholder={tp.editPlaceholder}
                            style={{ resize: 'vertical', overflowY: 'auto' }}
                          />
                        </div>
                      ) : (
                        <p className="text-base leading-relaxed whitespace-pre-wrap text-primary min-h-[500px]">
                          {prompt.content}
                        </p>
                      )}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>
            </CardContent>
          </Card>

          {/* 模板选择器：置于左侧容器内，作为固定高度区块 */}
          <Card className="mt-4 border border-primary/10 bg-secondary/5 shrink-0">
            <CardHeader className="py-4">
              <CardTitle className="text-base">选择模板并应用到内容</CardTitle>
            </CardHeader>
            <CardContent className="pt-0">
              {isLoadingTemplates ? (
                <div className="flex items-center text-sm text-muted-foreground">正在加载模板...</div>
              ) : templates.length === 0 ? (
                <div className="text-sm text-muted-foreground">暂无模板可用</div>
              ) : (
                <div className="flex items-center gap-3 w-full">
                  <div className="w-full max-w-sm">
                    <TemplateSelect
                      classNamePrefix="react-select"
                      options={templates.map(t => ({
                        value: t.id,
                        label: t.name,
                        searchText: `${t.name || ''} ${t.id || ''} ${t.content || ''}`
                      }))}
                      onChange={handleApplyTemplate}
                      placeholder="搜索或选择一个模板"
                      isClearable
                      isSearchable
                      menuPlacement="top"
                      menuPosition="fixed"
                      maxMenuHeight={200}
                      menuPortalTarget={menuPortalTarget}
                      styles={{ menuPortal: base => ({ ...base, zIndex: 9999 }) }}
                      filterOption={(option, rawInput) => {
                        const toHalfWidthDigits = (s) => s.replace(/[０-９]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 0xFF10 + 0x30));
                        const normalize = (s) => toHalfWidthDigits(String(s || '')).toLowerCase().replace(/\s+/g, '');
                        const input = normalize(rawInput);
                        if (!input) return true;
                        const label = normalize(option.label);
                        const extra = normalize(option.data?.searchText || option.searchText || '');
                        return label.includes(input) || extra.includes(input);
                      }}
                      noOptionsMessage={() => '没有匹配的模板'}
                    />
                  </div>
                  <Button
                    variant="secondary"
                    onClick={() => router.push('/template')}
                  >
                    管理模板
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="h-[calc(100vh-12rem)]">
          {prompt ? (
            <ChatTest 
              prompt={{...prompt, content: getCurrentPromptContent()}} 
              t={t} 
              onBeforeSend={checkAndHandleVariables}
              originalContent={getCurrentPromptContent()}
              onOpenModelSettings={() => setShowModelSettings(true)}
              modelConfig={modelConfig}
              ref={chatTestRef}
            />
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
                <p className="text-muted-foreground">加载中...</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 变量替换弹窗 */}
      <VariableReplacementModal
        isOpen={showVariableModal}
        onClose={() => setShowVariableModal(false)}
        variables={detectedVariables}
        onConfirm={handleVariableReplacement}
        promptContent={getCurrentPromptContent()}
      />

      {/* 模型设置弹窗 */}
      <Dialog open={showModelSettings} onOpenChange={setShowModelSettings}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-xl">模型配置信息</DialogTitle>
            <DialogDescription>
              修改当前提示词关联的模型配置参数
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-6 py-4">
            {!modelConfig || (!modelConfig.model && !modelConfig.channel) ? (
              <div className="text-sm text-muted-foreground">未关联模型配置</div>
            ) : null}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border rounded-md p-4">
              <div>
                <Label>
                  渠道名称
                  <span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>渠道名称</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <select
                  className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  value={modelConfig.channel}
                  onChange={e => {
                    const selectedChannel = channels.find(ch => ch.name === e.target.value);
                    setModelConfig({ 
                      ...modelConfig, 
                      channel: e.target.value,
                      channel_id: selectedChannel ? selectedChannel.id : null,
                      model: '' // 清空模型选择
                    });
                  }}
                  required
                >
                  <option value="">选择渠道</option>
                  {channels.map(channel => (
                    <option key={channel.id} value={channel.name}>
                      {channel.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <Label>
                  模型名称<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>选择渠道后获取可用模型列表</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <select
                  className={`block w-full rounded-md border border-input bg-background px-3 py-2 text-sm ${!modelConfig.channel_id ? 'opacity-50 cursor-not-allowed' : ''}`}
                  value={modelConfig.model}
                  onChange={e => setModelConfig({ ...modelConfig, model: e.target.value })}
                  disabled={!modelConfig.channel_id}
                  required
                >
                  <option value="">{modelConfig.channel_id ? '选择模型' : '请先选择渠道'}</option>
                  {models.map(model => (
                    <option key={model.model} value={model.model}>
                      {model.model}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <Label>
                  temperature<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>控制输出随机性：值越高越随机，值越低越确定，取值范围 [0, 2]</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.temperature} onChange={e => setModelConfig({ ...modelConfig, temperature: e.target.value })} />
              </div>
              <div>
                <Label>
                  max_tokens<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>生成内容的最大 token 数量（[10, 30000]，默认 2048）</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input required type="number" min={10} max={30000} value={modelConfig.max_tokens} onChange={e => setModelConfig({ ...modelConfig, max_tokens: e.target.value })} />
              </div>
              <div>
                <Label>
                  top_p<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>核采样，仅考虑累积概率达到阈值的 token，取值范围 [0, 2]</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.top_p} onChange={e => setModelConfig({ ...modelConfig, top_p: e.target.value })} />
              </div>
              <div>
                <Label>
                  presence_penalty<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>鼓励新话题：正值增加新主题概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.presence_penalty} onChange={e => setModelConfig({ ...modelConfig, presence_penalty: e.target.value })} />
              </div>
              <div>
                <Label>
                  frequency_penalty<span className="text-red-500 ml-1">*</span>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>惩罚重复：正值降低重复内容概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.frequency_penalty} onChange={e => setModelConfig({ ...modelConfig, frequency_penalty: e.target.value })} />
              </div>
              <div>
                <Label>
                  n
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>生成多个独立回复（如 n=3 返回 3 个选项），用于结果多样性选择</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input type="number" value={modelConfig.n} onChange={e => setModelConfig({ ...modelConfig, n: e.target.value })} />
              </div>
              <div>
                <Label>
                  stop (逗号分隔)
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>设置停止词，遇到即终止生成（如 ["\n", "。"]）</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input value={modelConfig.stop} onChange={e => setModelConfig({ ...modelConfig, stop: e.target.value })} />
              </div>
              <div>
                <Label>
                  logit_bias (JSON)
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>{'调整特定 token 的生成概率（如 {"1234": 2.0}）'}</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input value={modelConfig.logit_bias} onChange={e => setModelConfig({ ...modelConfig, logit_bias: e.target.value })} placeholder='{"123": -5}' />
              </div>
              <div>
                <Label>
                  stream
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>启用流式传输，逐块返回结果</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <select
                  className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  value={modelConfig.stream ? 'true' : 'false'}
                  onChange={e => setModelConfig({ ...modelConfig, stream: e.target.value === 'true' })}
                >
                  <option value="false">false</option>
                  <option value="true">true</option>
                </select>
              </div>
              <div>
                <Label>
                  api_key
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                      </TooltipTrigger>
                      <TooltipContent>调用第三方服务的密钥</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </Label>
                <Input value={modelConfig.api_key} onChange={e => setModelConfig({ ...modelConfig, api_key: e.target.value })} />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowModelSettings(false)}>
              取消
            </Button>
            <Button onClick={handleSaveModelConfig}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 提示词优化弹窗 */}
      <Modal isOpen={showOptimizeModal} onClose={() => setShowOptimizeModal(false)}>
        <ModalContent className="max-w-3xl max-h-[80vh]">
          <ModalHeader>
            <ModalTitle>提示词优化结果预览</ModalTitle>
          </ModalHeader>
          <div className="relative min-h-[200px] max-h-[50vh] overflow-y-auto">
            <Textarea
              value={optimizedContent}
              onChange={(e) => setOptimizedContent(e.target.value)}
              className="min-h-[200px] w-full"
              placeholder="优化结果将在这里显示..."
            />
          </div>
          <ModalFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setShowOptimizeModal(false)}
              className="mr-2"
            >
              取消
            </Button>
            <Button
              type="button"
              onClick={handleApplyOptimized}
              disabled={!optimizedContent.trim() || isOptimizing}
            >
              {isOptimizing ? '优化中...' : '应用优化'}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>

      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{tp.deleteConfirmTitle}</DialogTitle>
          </DialogHeader>
          <DialogDescription>{tp.deleteConfirmDescription}</DialogDescription>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteConfirm(false)}>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                handleDelete();
                setShowDeleteConfirm(false);
              }}
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
              </svg>
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}